package com.jing21.learn.fs.service;

import com.aliyun.oss.OSSClient;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.http.ProtocolType;
import com.aliyuncs.sts.model.v20150401.AssumeRoleRequest;
import com.aliyuncs.sts.model.v20150401.AssumeRoleResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.InputStream;

/**
 * Create By zhengjing on 2017/11/7 16:31
 */
@Component
public class FileSecurityService {

    @Autowired
    OSSClient ossClient;

    @Autowired
    DefaultAcsClient defaultAcsClient;

    // 当前 STS API 版本
    private static final String STS_API_VERSION = "2015-04-01";

    public boolean putFile(String bucket, String path, InputStream inputStream) {
        ossClient.putObject(bucket, path, inputStream);
        return true;
    }

    /**
     * STS
     */
    AssumeRoleResponse assumeRole(String roleArn, String roleSessionName, String policy,
                                  ProtocolType protocolType) throws com.aliyuncs.exceptions.ClientException {

        // 创建一个 AssumeRoleRequest 并设置请求参数
        final AssumeRoleRequest request = new AssumeRoleRequest();
        request.setVersion(STS_API_VERSION);
        request.setMethod(MethodType.POST);
        request.setProtocol(protocolType);
        request.setRoleArn(roleArn);
        request.setRoleSessionName(roleSessionName);
        request.setPolicy(policy);
        // 发起请求，并得到response
        final AssumeRoleResponse response = defaultAcsClient.getAcsResponse(request);
        return response;

    }

}
